package com.zhenwei.zscm.service;

import com.zhenwei.zscm.common.*;
import com.zhenwei.zscm.common.base.RestMsg;
import com.zhenwei.zscm.common.base.RestResult;
import com.zhenwei.zscm.common.utils.JwtHandler;
import com.zhenwei.zscm.common.utils.Utils;
import com.zhenwei.zscm.model.dto.roleAuth.RoleAuthDTO;
import com.zhenwei.zscm.model.dto.user.UserDTO;
import com.zhenwei.zscm.model.enums.RoleEnum;
import com.zhenwei.zscm.model.vo.user.QueryUserVO;
import com.zhenwei.zscm.model.vo.user.UserVO;
import com.zhenwei.zscm.repo.LogRepo;
import com.zhenwei.zscm.repo.RoleAuthRepo;
import com.zhenwei.zscm.repo.UserRepo;
import jakarta.validation.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
@AllArgsConstructor
public class UserService {
    private UserRepo userRepo;
    private RoleAuthRepo roleAuthRepo;
    private LogRepo logRepo;
    private final String LOG_TYPE = "用户管理";

    public RestResult login(String userName, String password) {
        // 参数不全
        if(userName == null || password == null || userName.isEmpty() || password.isEmpty()){
            return RestResult.fail(RestMsg.USERNAME_OR_PASSWORD_IS_EMPTY);
        }
        // 检查用户名密码
        String md5Pwd = Encrypt.md5(password);
        UserDTO user = userRepo.getUser(userName, md5Pwd);
        if(user == null){
            return RestResult.fail(RestMsg.USERNAME_OR_PASSWORD_INCORRECT);
        }
        var result = new HashMap<String, Object>();
        result.put("user", user);
        // 设置token
        String jwt = JwtHandler.generateJwt(user.getGuid());
        result.put("jwt", jwt);
        // 查询当前用户角色的权限
        var role = user.getRole();
        RoleAuthDTO roleAuth = roleAuthRepo.getRoleAuth(role);
        // 给前端只返回menu的权限即可
        result.put("menuAuth", roleAuth.getAuthMenu());
        logRepo.createAsync("LOGIN", "用户登录->"+user.getRealName(), user.getRealName(), user.getGuid());
        return RestResult.success(RestMsg.LOGIN_SUCCESS, result);
    }

    public RestResult getUserPageList(QueryUserVO vo){
        List<UserDTO> list = userRepo.getUserPageList(vo);
        return RestResult.success(list, vo.getTotalCount());
    }

    public RestResult createUser(UserVO vo){
        // 检查密码复杂度
        if(!Utils.isValidPassword(vo.getPassword())){
            return RestResult.fail(RestMsg.PASSWORD_LENGTH_INCORRECT);
        }
        // 检查用户登录名是否重复
        boolean exists = userRepo.checkUserNameExists(vo.getUserName(), "");
        if(exists){
            return RestResult.fail(RestMsg.USERNAME_EXISTS);
        }
        // 禁止用户创建管理员账户
        if(vo.getRole().equals(RoleEnum.ADMIN.name())){
            vo.setRole(RoleEnum.USER.name());
        }
        vo.setPassword(Encrypt.md5(vo.getPassword()));
        UserDTO user = userRepo.createUser(vo);
        if(user != null){
            logRepo.createAsync(LOG_TYPE, "添加用户->"+vo);
        }
        return RestResult.r(user != null);
    }

    public RestResult updateUser(UserVO vo){
        // 禁止用户创建管理员账户
        if(vo.getRole().equals(RoleEnum.ADMIN.name())){
            vo.setRole(RoleEnum.USER.name());
        }
        // 检查用户登录名是否重复
        boolean exists = userRepo.checkUserNameExists(vo.getUserName(), vo.getGuid());
        if(exists){
            return RestResult.fail(RestMsg.USERNAME_EXISTS);
        }
        boolean b = userRepo.updateUser(vo);
        if(b){
            logRepo.createAsync(LOG_TYPE, "修改用户->"+vo);
        }
        return RestResult.r(b);
    }
    public RestResult  updateUserPwd(UserVO vo){
        // 检查密码复杂度
        if(!Utils.isValidPassword(vo.getPassword())){
            return RestResult.fail(RestMsg.PASSWORD_LENGTH_INCORRECT);
        }
        vo.setPassword(Encrypt.md5(vo.getPassword()));
        boolean b = userRepo.updateUserPwd(vo);
        if(b){
            logRepo.createAsync(LOG_TYPE, "修改用户密码->"+vo);
        }
        return RestResult.r(b);
    }

    public RestResult delete(String userId) {
//        if(StrUtil.isBlank(userId)){
//            return RestResult.fail(RestMsg.PARAM_IS_EMPTY);
//        }
        boolean b = userRepo.delete(userId);
        if(b){
            logRepo.createAsync(LOG_TYPE, "删除用户->"+userId);
        }
        return RestResult.r(b);
    }

    public RestResult detail(@NotEmpty(message = "用户ID不能为空") String userId) {
        UserDTO user = userRepo.getUserById(userId);
        return RestResult.success(user, 0);
    }
}
